﻿using LabelManager2;
using MaterialSkin;
using MaterialSkin.Controls;
using Newtonsoft.Json;
using SoftwareInfo;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Net.Http;
using System.Printing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KBLPrint
{
    public partial class MainForm : MaterialForm
    {
        private readonly MaterialSkinManager materialSkinManager;

        public MainForm()
        {
            InitializeComponent();

            // Initialize MaterialSkinManager
            materialSkinManager = MaterialSkinManager.Instance;

            // Set this to false to disable backcolor enforcing on non-materialSkin components
            // This HAS to be set before the AddFormToManage()
            materialSkinManager.EnforceBackcolorOnAllComponents = true;

            // MaterialSkinManager properties
            //materialSkinManager.AddFormToManage(this);

            //materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
            //materialSkinManager.ColorScheme = new ColorScheme(
            //           Primary.BlueGrey800,
            //           Primary.BlueGrey900,
            //           Primary.BlueGrey500,
            //           Accent.LightBlue200,
            //           TextShade.WHITE);
        }

    
        string sLabPath = string.Empty;

        private string sPassword = "KBL2412";
        SqlLiteManager sqlLiteManager = new SqlLiteManager();
        string sDbPath = System.Windows.Forms.Application.StartupPath + "\\InfoLocal.db";


    
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.MaximumSize = new Size(800, 570);
                this.WindowState = FormWindowState.Maximized;
                CheckCerInfo();
                string sErrInfo = string.Empty;
                bool bRst = sqlLiteManager.OpenDB(sDbPath, sPassword, out sErrInfo);
                if (!bRst)
                {
                    ShowSysmsg("初始化数据库连接失败！" + sErrInfo);
                    return;
                }

                GetPortName();
                GetPrinterName();

                ReadSysPara();

                init_codesoft();

                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                }

                dataGridView1.RowsDefaultCellStyle.Font = new Font("宋体", 11, FontStyle.Regular);
                dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 11, FontStyle.Regular);

                materialButton6_Click(null , null);

            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化失败！ " + ex.Message);
            }
        }

     

        public void GetPortName()
        {
            foreach (string portName in SerialPort.GetPortNames())
            {
                cbxSerName.Items.Add(portName);
            }
        }

        public void GetPrinterName()
        {
            try
            {
                LocalPrintServer printServer = new LocalPrintServer();
                PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local });
                foreach (PrintQueue printer in printQueuesOnLocalServer)
                {
                    comboBox2.Items.Add(printer.Name);
                }
                if (comboBox2.Items.Count > 0)
                {
                    comboBox2.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取打印机列表失败！" + ex.Message);
            }
        }

        public void CheckCerInfo()
        {
            try
            {
                #region 注册证书
                string sTempExeName = Path.GetFileName(System.Windows.Forms.Application.ExecutablePath);
                string sExeName = sTempExeName.Substring(0, sTempExeName.Length - 4);
                SoftwareRestriction.sCerPath = System.Windows.Forms.Application.StartupPath + "\\" + sExeName + ".cer";
                string sOutMsg = string.Empty;
                string sUserType = string.Empty;
                bool isRegistOk = SoftwareInfo.SoftwareRestriction.IsExpires(SoftwareInfo.SoftwareRestriction.sCerPath, sExeName, ref sOutMsg, ref sUserType);
                //Program.set_main_info(sOutMsg);
                if (isRegistOk)
                {
                    MessageBox.Show(sOutMsg);
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                    return;
                }


                string numberString = System.Text.RegularExpressions.Regex.Replace(sOutMsg, @"[^0-9]+", "");
                if (!string.IsNullOrEmpty(numberString))
                {
                    int numberInt = int.Parse(numberString);
                    if (numberInt <= 7)
                    {
                        MessageBox.Show(sOutMsg);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("CheckCerInfo " + ex.Message);
            }
        }

      

        void ShowSysmsg(string msg)
        {
            msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ">>" + msg + "\r\n";
            if (txtMsg.InvokeRequired)
            {
                txtMsg.BeginInvoke(new MethodInvoker(delegate
                {
                    txtMsg.AppendText(msg);
                }));
            }
            else
            {
                txtMsg.AppendText(msg);
            }
        }


        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="ProcessName">进程名称</param>
        private void killEXE(string ProcessName)
        {
            Process[] processes;
            processes = Process.GetProcesses();
            string str = "";
            foreach (Process p in processes)
            {
                try
                {
                    str = p.ProcessName;
                    if (str.Equals(ProcessName))
                    {
                        RunCmd("taskkill /pid " + p.Id + " -f");
                    }
                }
                catch (Exception)
                {
                    //this.lst1.Items.Add(ex.Message.ToString());//某些系统进程禁止访问，所以要加异常处理
                }
            }
        }

        /// <summary>
        /// 用命令去结束进程，而不是用C#自带的类。这种比较稳定。
        /// </summary>
        /// <param name="command">命令代码</param>
        /// <returns>命令执行结果</returns>
        public string RunCmd(string command)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c " + command;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            return p.StandardOutput.ReadToEnd();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (serialPortScan.IsOpen)
                    serialPortScan.Close();
                killEXE("lppa");
            }
            finally
            {
                killEXE("lppa");
            }
        }

        List<string> listSn = new List<string>();

        private void serialPortScan_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);
            try
            {

                //byte[] byData = new byte[100];
                //int nReadCnt = serialPortScan.Read(byData, 0, byData.Length);
                //byte[] byRec = new byte[nReadCnt];
                //Array.Copy(byData, byRec, nReadCnt);
                //ShowSysmsg("收到条码数据: " + BitConverter.ToString(byRec).Replace("-", " "));
                //if (nReadCnt == 16)
                //{
                //    string sn = System.Text.Encoding.ASCII.GetString(byRec);
                //    ShowSysmsg("条码内容为：" + sn);

                //    //this.Invoke(new MethodInvoker(delegate
                //    //{

                //    //}));

                //    //AddToDgv(sn);

                //    //GetProductInfo("");


                //    //Thread mythread = new Thread(new ParameterizedThreadStart(Run));
                //    //mythread.IsBackground = true;
                //    //mythread.Start(sn);

                //    //打印
                //    //Thread thread = new Thread(print);
                //    //thread.IsBackground = true;
                //    //thread.Start(sShowWeigh);
                //}
                //else
                //{
                //    string sMsg = "接收到的长度为:" + nReadCnt.ToString() + ",应为16";
                //    ShowSysmsg(sMsg);
                //}

                string sn = serialPortScan.ReadExisting().TrimEnd('\r').Trim();
                ShowSysmsg("扫描到条码：" + sn);
                if (listSn.Contains(sn))
                {
                    ShowSysmsg("条码扫描重复：" + sn);
                    return;
                }
                listSn.Add(sn);

                this.Invoke(new MethodInvoker(delegate
                {
                    materialLabel6.Text = listSn.Count.ToString();
                }));

                if (listSn.Count == nPrintCnt)  //提交
                {
                    ShowSysmsg("已经达到预设条件，开始请求打印数据！");
                    //复制一份扫描后的条码，提交打印数据的请求后清空列表，等待下一次扫描，重置扫描次数
                    GetProductInfo("");
                    
                }

            }
            catch (Exception ex)
            {
                ShowSysmsg(ex.Message);
            }
        }


        //保存配置
        private void materialButton1_Click(object sender, EventArgs e)
        {
            MaterialSnackBar SnackBarMessage;
            string sql = string.Empty;
            StringBuilder stringBuilder = new StringBuilder();

            sql = "update t_SysPara set paravalue = '" + cbxSerName.Text + "' where  paraname = 'portName' ; ";
            stringBuilder.AppendLine(sql);
            sql = "update t_SysPara set paravalue = '" + materialComboBox2.Text + "' where  paraname = 'portRate'  ;";
            stringBuilder.AppendLine(sql);
            sql = "update t_SysPara set paravalue = '" + comboBox2.Text + "' where  paraname = 'printName'  ;";
            stringBuilder.AppendLine(sql);
            sql = "update t_SysPara set paravalue = '" + materialTextBox1.Text + "' where  paraname = 'url'  ;";
            stringBuilder.AppendLine(sql);

            sqlLiteManager.ExecuteSql(stringBuilder.ToString());

            SnackBarMessage = new MaterialSnackBar("保存成功！", "OK", true);
            SnackBarMessage.Show(this);
        }


        //保存配置的全局变量
        DataTable dataParaTable = new DataTable();
        public void ReadSysPara()
        {
            string sql = "select * from t_SysPara;";

            string sMsg = string.Empty;
            sqlLiteManager.GetDataSet(sql , out dataParaTable, out sMsg);
            cbxSerName.Text = dataParaTable.Rows[0]["paravalue"].ToString();
            materialComboBox2.Text = dataParaTable.Rows[1]["paravalue"].ToString();
            comboBox2.Text = dataParaTable.Rows[2]["paravalue"].ToString();
            materialTextBox1.Text = dataParaTable.Rows[3]["paravalue"].ToString();
        }


        //public void ShowDialog(string msg,string title)
        //{
        //    this.BeginInvoke(new MethodInvoker(delegate
        //    {
        //        MaterialSnackBar SnackBarMessage = new MaterialSnackBar(msg, title, true);
        //        SnackBarMessage.Show(this);
        //    }));
        //}


        int nPrintCnt = 0;

        //开始
        private void materialButton6_Click(object sender, EventArgs e)
        {
            txtMsg.Text = string.Empty;
            if (init_com())
            {
                return;
            }

            nPrintCnt = Convert.ToInt32(materialComboBox3.Text);

            ShowSysmsg("系统启动成功！");
            materialButton6.Enabled = false;
            materialButton7.Enabled = true;
        }


        bool init_com()
        {
            bool isfail = false;
            try
            {
                if (serialPortScan.IsOpen)
                {
                    serialPortScan.Close();
                }
                serialPortScan.PortName = cbxSerName.Text.Trim();
                serialPortScan.BaudRate = Convert.ToInt32(materialComboBox2.Text.Trim());
                serialPortScan.Open();
            }
            catch (Exception ex)
            {
                isfail = true;
                ShowSysmsg(ex.Message + "\r\n");
            }
            return isfail;
        }


        //停止
        private void materialButton7_Click(object sender, EventArgs e)
        {
            listSn.Clear();
            materialLabel6.Text = "0";

            if (serialPortScan.IsOpen)
                serialPortScan.Close();

            materialButton6.Enabled = true;
            materialButton7.Enabled = false;
            ShowSysmsg("系统停止成功！");
        }


        //string sPath = Application.StartupPath + "\\download.pdf";

        public async void GetProductInfo(object objValue)
        {
            try
            {
                string sn = objValue.ToString();
                var obj = new
                {
                    ProduceBillNo = sn
                };

                // 使用示例
                var client = new HttpClient();
                var apiClient = new ApiClient(client);
                var result = await apiClient.PostJsonAsync(dataParaTable.Rows[3]["paravalue"].ToString(), obj);
                Console.WriteLine(result);

                ReturnData returnData = JsonConvert.DeserializeObject<ReturnData>(result);
                if (returnData.IsSuccess == "false")
                {
                    ShowSysmsg("请求标签失败！失败Code为:" + returnData.Code + " 失败原因为:" + returnData.Message);
                    return;
                }

                //bool bRst = DownLoadFile(returnData.Data.XAuthToken, returnData.Data.Url);
                //if (!bRst)
                //{
                //    return;
                //}

                //打印
                Print(sn);
            }
            catch (Exception ex)
            {
                ShowSysmsg("Run " + ex.Message);
            }

        }

        //public bool DownLoadFile(string sToken, string sUrl)
        //{
        //    File.Delete(sPath);
        //    try
        //    {

        //        HttpClient httpClient = new HttpClient();
        //        //httpClient.BaseAddress = new Uri("https://eos-scp-core-shenzhen-futian1-oss.sf-express.com/");

        //        HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
        //        httpRequestMessage.Method = new HttpMethod("GET");
        //        httpRequestMessage.Headers.Add("context-type", "application/pdf");
        //        httpRequestMessage.Headers.Add("X-Auth-token", sToken);
        //        httpRequestMessage.RequestUri = new Uri(sUrl);

        //        HttpResponseMessage httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;

        //        if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
        //        {
        //            System.IO.Stream stream = httpResponseMessage.Content.ReadAsStreamAsync().Result;
        //            using (System.IO.FileStream fs = new System.IO.FileStream(sPath, System.IO.FileMode.CreateNew))
        //            {
        //                byte[] buffer = new byte[stream.Length];
        //                stream.Read(buffer, 0, buffer.Length);
        //                fs.Write(buffer, 0, buffer.Length);
        //            }
        //        }

        //        ShowSysmsg("标签下载成功！");
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowSysmsg("标签下载失败！" + ex.Message);
        //        return false;
        //    }

        //}

        public void Print(string sn)
        {
            try
            {
               

                AddToDgv(sn);
                ShowSysmsg("打印成功！");

            }
            catch (Exception ex)
            {
                ShowSysmsg("打印失败！" + ex.Message);
            }
        }


        public void AddToDgv(string sn)
        {
            this.Invoke((Delegate)(MethodInvoker)delegate
            {
                if (dataGridView1.Rows.Count >= 100)
                {
                    dataGridView1.Rows.Clear();
                }

                object[] obj = new object[3];
                obj[0] = dataGridView1.Rows.Count + 1;
                obj[1] = sn;
                obj[2] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                dataGridView1.Rows.Insert(0, obj);
               
            });
        }

        private void materialButton2_Click(object sender, EventArgs e)
        {

            //Thread mythread = new Thread(new ParameterizedThreadStart(GetOrderNumber));
            //mythread.IsBackground = true;
            //mythread.Start();

           



            //string sn = materialTextBox5.Text;
            //if (string.IsNullOrEmpty(sn))
            //{
            //    MaterialSnackBar SnackBarMessage = new MaterialSnackBar("条码不能为空！");
            //    SnackBarMessage.Show(this);
            //    return;
            //}


            //Thread mythread = new Thread(new ParameterizedThreadStart(Run));
            //mythread.IsBackground = true;
            //mythread.Start(sn);
        }


        LabelManager2.Application Myapp = new LabelManager2.Application();
        Document doc = null;
        string sLabelPath = System.Windows.Forms.Application.StartupPath + "\\Label.Lab";


        void init_codesoft()
        {
            try
            {
                killEXE("lppa");
                Myapp = new LabelManager2.Application();
                Myapp.Documents.Open(sLabelPath);
                doc = Myapp.ActiveDocument;
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化打印模板出错，请先安装条码打印软件！ " + ex.Message);
            }
        }

        void print(object objWeight)
        {
            try
            {
                string sWeight = objWeight.ToString();
                string strDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

                Data data = new Data();
                data.ProduceName = "E111";
                data.PartNumber = "9246810-HA01-D";
                data.MapNumber = "CH134";
                data.ProductionDate = "20241116";
                data.PackingQuantity = "4套";

                //this.Invoke((Delegate)(MethodInvoker)delegate
                //{

                //});

                doc.Variables.Item("s1").Value = data.ProduceName;
                doc.Variables.Item("s2").Value = data.PartNumber;
                doc.Variables.Item("s3").Value = data.MapNumber;
                doc.Variables.Item("s4").Value = data.ProductionDate;
                doc.Variables.Item("s5").Value = data.PackingQuantity;
                doc.PrintDocument();
                ShowSysmsg("打印完成！");

                ////更新界面显示
                //this.Invoke((Delegate)(MethodInvoker)delegate
                //{
                //    txtBox5.Text = uNo.ToString();
                //});
            }
            catch (Exception ex)
            {
                ShowSysmsg("打印赋值出错！" + ex.Message);
            }
        }


    }
}
